<?php

namespace app\api\controller;

use app\admin\model\Admin;
use app\common\controller\Api;
use app\common\func\Constant;
use app\common\func\Lib;
use app\common\func\Libs;
use app\common\func\Tools;
use app\common\func\WxPay;
use app\common\model\Order as ModelOrder;
use app\common\model\OrderAddress;
use app\common\model\OrderCart;
use app\common\model\OrderProduct;
use app\common\model\UserAddress;
use EasyWeChat\Kernel\Support\XML;
use think\Db;

class Order extends Api
{
    protected $noNeedLogin = ["saveOrder", "notify","notifyRefund"];
    protected $noNeedRight = '*';

    public function getUnFinishOrder(){
        $userIds = [];
        $child = Tools::getUserChild($this->auth->id,2);
        foreach ($child as $key => $val){
            $userIds[] = $val['id'];
        }

        $count = \app\common\func\Order::getUserOrderCount($userIds,1);

        if($count > 0){
            $this->success("未完成订单","通知：您有【{$count}】条订单未处理！");
        }else{
            $this->error("未完成订单");
        }
    }

    public function getOrderSn(){
        $orderProductId = $this->request->post("order_product_id");

        if(!$orderProductId){
            $this->error("缺少参数！");
        }

        $this->success("sn列表",Libs::getOrderProductSnList($orderProductId));
    }

    public function orderCount(){
        $userIds = [];
        $child = Tools::getUserChild($this->auth->id,2);
        foreach ($child as $key => $val){
            $userIds[] = $val['id'];
        }

        $list = [
            "my" => [
                "total" => \app\common\func\Order::getUserOrderCount([$this->auth->id]),
                "unfinished" => \app\common\func\Order::getUserOrderCount([$this->auth->id],1),
                "completed" => \app\common\func\Order::getUserOrderCount([$this->auth->id],2),
            ],
            "team" => [
                "total" => \app\common\func\Order::getUserOrderCount($userIds),
                "unfinished" => \app\common\func\Order::getUserOrderCount($userIds,1),
                "completed" => \app\common\func\Order::getUserOrderCount($userIds,2),
            ]
        ];

        $this->success("订单统计",$list);
    }

    public function getSelfFetchAddress(){
        $admin = Admin::get(13);

        $this->success("自取地址",$admin->address);
    }

    public function editCart()
    {
        $type = $this->request->post("type");
        $cartId = $this->request->post("cart_id");

        if (!$type || !$cartId) {
            $this->error("缺少参数！");
        }

        $cart = \app\common\func\Order::getCartById($this->auth->id, $cartId);
        $product = Lib::getProductById($cart->product_id);

        if ($type == "add") {
            $cart->number += $product->min;
            $result = $cart->save();
        } elseif ($type == "reduce") {
            $cart->number -= $product->min;
            $result = $cart->save();
        } elseif ($type == "del") {
            $result = $cart->delete();
        } else {
            $this->error("操作类型错误！");
        }

        if ($result) {
            $this->success("操作成功！");
        } else {
            $this->error("操作失败！");
        }
    }

    public function getCart()
    {
        $list = \app\common\func\Order::getCartByUser($this->auth->id);

        $this->success("购物车列表", processImage('image', $list));
    }

    public function addCart()
    {
        $productList = $this->request->post("product/a");

        if (count($productList) == 0) {
            $this->error("未选择产品！");
        }

        $result = false;
        $data = [];
        try {
            foreach ($productList as $key => $val) {
                $cart = \app\common\func\Order::getCartByProduct($this->auth->id, $val['product_id']);
                if ($cart) {
                    $cart->number += $val['product_num'];
                    $cart->save();
                } else {
                    $data[] = [
                        "user_id" => $this->auth->id,
                        "product_id" => $val['product_id'],
                        "number" => $val['product_num'],
                    ];
                }
            }

            if (count($data) > 0) {
                $cart = new OrderCart();
                $cart->saveAll($data);
            }

            $result = true;
        } catch (\Exception $e) {
        }

        if ($result) {
            $this->success("加入购物车成功！");
        } else {
            $this->error("加入失败！");
        }
    }

    public function pay()
    {
        $orderId = $this->request->post("order_id");
        $payType = $this->request->post("pay_type");

        if (!$payType || !$orderId) {
            $this->error("缺少参数！");
        }

        $order = \app\common\func\Order::getOrderById($orderId);
        if (!$order || $order->user_id != $this->auth->id) {
            $this->error("订单错误！");
        }

        if ($order->pay_state != 0) {
            $this->error("该订单已完成！");
        }

        if ($payType == 1) { //余额支付
            $balance = \app\common\func\Order::getUserBalance($this->auth->id);
            if (!$balance || ($balance && $balance->money < $order->pay_price)) {
                $this->error("用户余额不足！");
            }

            $result = false;
            $msg = "";
            Db::startTrans();
            try {
                $order->pay_type = $payType;
                $order->pay_state = 1;
                $order->pay_time = time();
                $order->save();

                $option = [
                    "uid"		=> $order->user_id, // 收入 或 支出 代理ID
                    "typs"		=> 10, // 变更类型 1=分润,2=流量卡,3=达标,4=借款,5=还款,6=赠送,7=提现,8=认购,9=调价，10=采购
                    "isChg" 	=> 2, // 1 收入  2 减少
                    "remark" 	=> "采购设备金额",	// 备注  => 没有备注传空字符串
                    "chgAmt" 	=> $order->pay_price,	// 变更金额
                    "ids" 		=> $order->id,	// 操作订单主ID | 分润、达标、流量卡 传入产品ID
                ];
                \app\common\controller\Balance::instance()->sub_and_logs($option);

                $result = true;

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $msg = $e->getMessage();
            }

            if ($result) {
                $this->success("支付成功！");
            } else {
                $this->error("支付失败:" . $msg);
            }
        } elseif ($payType == 2) { //微信支付
            $openid = $this->request->post("openid");
            if (!$openid) {
                $this->error("缺少openid!");
            }

            $order->pay_type = $payType;
            $order->save();

            $rollbackUrl = Config("app_url")."/api/order/notify";//回调地址
            $wePay = new WxPay($rollbackUrl);
            $result = $wePay->pushOrder("设备采购",$openid, $order->order_num, $order->pay_price);

            $this->success("微信支付", $result);
        }elseif ($payType == 3){//认购量支付
            $result = false;
            $msg = "";
            Db::startTrans();
            try {
                $orderNumber = \app\common\func\Order::getOrderTotalNumber($order->id);
                $buyNumber = \app\common\func\Order::getBuyNumber($this->auth->id);

                if($buyNumber->nums < $orderNumber){
                    $this->error("认购量不足，请使用其他支付方式！");
                }

                $buyNumber->nums -= $orderNumber;
                $buyNumber->save();

                $order->pay_type = $payType;
                $order->pay_state = 1;
                $order->pay_time = time();
                $order->save();

                $result = true;

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $msg = $e->getMessage();
            }

            if ($result) {
                $this->success("支付成功！");
            } else {
                $this->error("支付失败:" . $msg);
            }

        } else {
            $this->error("不支持该支付类型！");
        }
    }

    public function saveOrder()
    {
        $productList = $this->request->post("product/a",[]);

        $productData = [];
        $orderPrice = 0;
        $freight = 0;
        $totalNum = 0;
        $orderNum = \app\common\func\Order::getOrderNum();

        if (count($productList) == 0) {
            $this->error("未选择产品！");
        }

        if(!in_array($this->auth->buy_level,Constant::$buyLevel)){
            $this->error("请认购等级后在进行操作！");
        }

        foreach ($productList as $key => $val) {
            $product = Lib::getProductById($val['id']);
            if (!$product) {
                $this->error("您选择的产品不存在！");
            }
            $totalPrice = $product->price * $val['nums'];
            $productData[] = [
                "user_id" => $this->auth->id,
                "product_id" => $val['id'],
                "product_name" => $product->name,
                "number" => $val['nums'],
                "single_price" => $product->price,
                "total_price" => $totalPrice,
            ];
            $orderPrice += $totalPrice;
            $totalNum += $val['nums'];
        }

        $order = [];
        $result = false;
        $msg = "";
        Db::startTrans();
        try {
            $order = new \app\common\model\Order();
            $order->user_id = $this->auth->id;
            $order->order_num = $orderNum;
            $order->price = $orderPrice;
            $order->total_num = $totalNum;
            $order->pay_price = $orderPrice + $freight;
            $order->save();

            foreach ($productData as $key => &$val) {
                $val['order_id'] = $order->id;
            }
            unset($val);

            $orderProduct = new OrderProduct();
            $orderProduct->saveAll($productData);

            $result = true;

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $msg = $e->getMessage();
        }

        if ($result) {
            $this->success("下单成功！", $order);
        } else {
            $this->error("下单失败:" . $msg);
        }
    }

    public function getAddress()
    {
        $list = \app\common\func\Order::getUserAddress($this->auth->id);

        $this->success("用户收货地址", $list);
    }

    public function addAddress()
    {
        $name = $this->request->post("name");
        $mobile = $this->request->post("mobile");
        $province = $this->request->post("province");
        $city = $this->request->post("city");
        $district = $this->request->post("district");
        $address = $this->request->post("address");
        $default = $this->request->post("default", 0);
        $type = $this->request->post("type", 1);
        $order_id = $this->request->post("order_id");

        if (!$name || !$mobile) {
            $this->error("缺少联系人信息");
        }

        if (!$province || !$city || !$district || !$address) {
            $this->error("收货地址不能为空");
        }

        $result = false;
        try {
            if ($default > 0) {
                $list = \app\common\func\Order::getUserDefaultAddress($this->auth->id);
                if (count($list) > 0) {
                    foreach ($list as $key => $val) {
                        $val->default = 0;
                        $val->save();
                    }
                }
            }

            $userAddress = new UserAddress();
            $userAddress->user_id = $this->auth->id;
            $userAddress->name = $name;
            $userAddress->mobile = $mobile;
            $userAddress->province = $province;
            $userAddress->city = $city;
            $userAddress->district = $district;
            $userAddress->address = $address;
            $userAddress->default = $default > 0 ? 1 : 0;
            $result = $userAddress->save();
            if ($result) {
                if ($type == 2 && $order_id > 0) {
                    $orderAddressData = OrderAddress::where(["user_id" => $this->auth->id, "order_id" => $order_id])->find();
                    if (!empty($orderAddressData)) {
                        $orderAddressData->name = $name;
                        $orderAddressData->mobile = $mobile;
                        $orderAddressData->address = $province . $city . $district . $address;
                        $orderAddressData->save();
                    } else {
                        $orderAddressDatas = new OrderAddress();
                        $orderAddressDatas->user_id = $this->auth->id;
                        $orderAddressDatas->order_id = $order_id;
                        $orderAddressDatas->name = $name;
                        $orderAddressDatas->mobile = $mobile;
                        $orderAddressDatas->address = $province . $city . $district . $address;
                        $orderAddressDatas->save();
                    }
                }
            }
        } catch (\Exception $e) {
            $e->getMessage();
        }

        if ($result) {
            $this->success("添加成功！");
        } else {
            $this->error("添加失败！");
        }
    }

    public function getProductData()
    {
        $class = Db::name("pay_company")->field("id,name")->where(["status" => 1, "sell_state" => 1])->order("create_time desc")->select();
        foreach ($class as $key => $val) {
            $proData = Db::name("product")->field("id,name,price,min,image,0 as nums,1 as isshow")->where(["pay_id" => $val["id"], "status" => 1, "sell_state" => 1])->order("create_time desc")->select();
            $class[$key]["proData"] = processImage("image", $proData);
        }
        $this->success("商品", $class);
    }

    public function getCertNums()
    {
        $nums = OrderCart::where(["user_id" => $this->auth->id])->sum('number');
        $nums = empty($nums) ? 0 : $nums;
        $this->success("购物车数量", $nums);
    }

    // 获取默认地址
    public function getDefaultAddress()
    {
        $data = UserAddress::where(["user_id" => $this->auth->id, 'default' => 1])->find();
        $this->success("默认地址", $data);
    }

    // 获取收货地址信息
    public function getAddressInfo()
    {
        $id = $this->request->post("id");
        $data = UserAddress::where(["id" => $id])->find();
        $this->success("地址信息", $data);
    }

    // 删除收货地址
    public function delAddress()
    {
        $id = $this->request->post("id");
        $res = UserAddress::where(["id" => $id])->delete();
        if ($res) {
            $this->success("删除成功");
        } else {
            $this->error("删除失败");
        }
    }

    // 修改收货地址
    public function editAddress()
    {
        $id = $this->request->post("id");
        $name = $this->request->post("name");
        $mobile = $this->request->post("mobile");
        $province = $this->request->post("province");
        $city = $this->request->post("city");
        $district = $this->request->post("district");
        $address = $this->request->post("address");
        $default = $this->request->post("default", 0);

        if (!$name || !$mobile) {
            $this->error("缺少联系人信息");
        }

        if (!$province || !$city || !$district || !$address) {
            $this->error("收货地址不能为空");
        }

        $result = false;
        try {
            if ($default > 0) {
                $list = \app\common\func\Order::getUserDefaultAddress($this->auth->id);
                if (count($list) > 0) {
                    foreach ($list as $key => $val) {
                        $val->default = 0;
                        $val->save();
                    }
                }
            }

            $datas = [
                "name" => $name,
                "mobile" => $mobile,
                "province" => $province,
                "city" => $city,
                "district" => $district,
                "address" => $address,
                "default" => $default
            ];
            $result = UserAddress::where(["id" => $id])->update($datas);
        } catch (\Exception $e) {
            $e->getMessage();
        }

        if ($result) {
            $this->success("保存成功！");
        } else {
            $this->error("保存失败！");
        }
    }

    public function notify()
    {
        $data = file_get_contents("php://input");
        $message = XML::parse($data);

        $order = \app\common\func\Order::getOrderByOrderNum($message['out_trade_no']);

        $result = [
            'return_code' => 'SUCCESS',
            'return_msg' => "",
        ];

        if (!$order || $order->pay_state == 1) {
            return XML::build($result);
        }

        if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
            // 用户是否支付成功
            if ($message['result_code'] === 'SUCCESS') {
                $order->trade_no = $message['transaction_id']; // 更新支付时间为当前时间
                $order->pay_time = strtotime($message['time_end']);
                $order->pay_state = 1;

                // 用户支付失败
            } else {
                $order->pay_state = 3;
                $order->remark = "支付失败！";
            }
        } else {
            $result = [
                'return_code' => 'FAIL',
                'return_msg' => "通信失败，请稍后再通知我",
            ];
        }

        $order->save(); // 保存订单

        return XML::build($result);
    }

    public function notifyRefund()
    {
        $data = file_get_contents("php://input");
        $message = XML::parse($data);

        $info = Tools::wxNotifyDecrypt($message['req_info'],Constant::$key);
        $info = XML::parse($info);

        $order = \app\common\func\Order::getOrderByOrderNum($info['out_trade_no']);
        $order->pay_state = 4;
        $order->save();

        $result = [
            'return_code' => 'SUCCESS',
            'return_msg' => "",
        ];

        return XML::build($result);
    }

    // 获取配送方式
    public function getDistributionMode()
    {
        $data = [
            ["id" => 1, "label" => "自取", "price" => 0],
            ["id" => 2, "label" => "运营中心(快递)", "price" => 15]
        ];
        $this->success("配送方式", $data);
    }

    // 获取订单列表
    public function getOrderList()
    {
        $pay_state = $this->request->post("pay_state", 'all');
        $page = $this->request->post('page', "1");
        $pageSize = $this->request->post('page_size', "15");
        $type = $this->request->post('type');//1我的，2团队

        if ($pay_state == 'all') {
            $where['a.pay_state'] = [">", 0];
        } else {
            $where['a.pay_state'] = $pay_state;
        }

        if($type == 1){
            $where["a.user_id"] = $this->auth->id;
        }elseif ($type == 2){
            $userIds = [];
            $child = Tools::getUserChild($this->auth->id,2);
            foreach ($child as $key => $val){
                $userIds[] = $val['id'];
            }
            $where["a.user_id"] = ["in", $userIds];
        }

        $data = Db::name("order")->alias("a")
            ->join("order_product b", "b.order_id = a.id", 'LEFT')
            ->join("product c", "c.id = b.product_id", 'LEFT')
            ->join("pay_company d", "d.id = c.pay_id", 'LEFT')
            ->join("user u", "u.id = a.user_id", 'LEFT')
            ->field("a.*,FROM_UNIXTIME(a.create_time) create_time_txt,FROM_UNIXTIME(a.finish_time) finish_time_txt,c.name,c.image,b.number,b.single_price,b.total_price,d.name as cname,u.nickname as mobile")
            ->where($where)->order("a.create_time desc")->page($page, $pageSize)->select();

        $this->success("订单列表", processImage("image", $data));
    }

    // 获取订单详情
    public function getOrderDetail()
    {
        $orderId = $this->request->post("order_id");
        if ($orderId > 0) {
            $order = ModelOrder::where('id', $orderId)->field("*,FROM_UNIXTIME(create_time) create_time_txt,FROM_UNIXTIME(finish_time) finish_time_txt")->find()->toArray();
            $proData = Db::name("order_product")->alias("a")
                ->join("product b", 'b.id = a.product_id', 'LEFT')
                ->join("user u", "u.id = a.user_id", 'LEFT')
                ->where(["a.order_id" => $order["id"]])
                ->field("a.*,b.image,u.nickname as mobile")
                ->select();
            $order["proData"] = processImage("image", $proData);
            $order["address"] = OrderAddress::where(["order_id" => $order["id"]])->find();
            $this->success("订单信息", $order);
        } else {
            $this->error("参数错误");
        }
    }

    // 取消订单
    public function cancelOrder()
    {
        $orderId = $this->request->post("order_id");

        $order = \app\common\func\Order::getOrderById($orderId);

        if(!$order){
            $this->error("订单不存在！");
        }

        if($order->user_id != $this->auth->id){
            $this->error("订单不属于您！");
        }

        if($order->pay_state != 1){
            $this->error("该订单不允许取消！");
        }

        if($order->pay_type == 1){
            $result = false;
            $msg = "";
            Db::startTrans();
            try {
                $order->pay_state = 4;
                $order->save();

                $option = [
                    "uid"		=> $order->user_id, // 收入 或 支出 代理ID
                    "typs"		=> 11, // 变更类型 1=分润,2=流量卡,3=达标,4=借款,5=还款,6=赠送,7=提现,8=认购,9=调价，10=采购，11=采购退款
                    "isChg" 	=> 1, // 1 收入  2 减少
                    "remark" 	=> "退款:采购设备",	// 备注  => 没有备注传空字符串
                    "chgAmt" 	=> $order->pay_price,	// 变更金额
                    "ids" 		=> $order->id,	// 操作订单主ID | 分润、达标、流量卡 传入产品ID
                ];
                \app\common\controller\Balance::instance()->add_and_logs($option);

                $result = true;

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $msg = $e->getMessage();
            }

            if ($result) {
                $this->success("取消成功！");
            } else {
                $this->error("取消失败:" . $msg);
            }
        }elseif ($order->pay_type == 2){
            $rollbackUrl = Config("app_url")."/api/order/notifyRefund";//回调地址
            $refundNum = \app\common\func\Order::getOrderRefundNum();

            $wePay = new WxPay($rollbackUrl);
            $result = $wePay->refundOrder($order->trade_no,$refundNum,$order->pay_price);

            if($result['return_code'] == "SUCCESS" && $result['result_code'] == "SUCCESS"){
                $this->success("取消成功！");
            }else{
                $this->error("取消失败:" . $result['return_msg']);
            }

        }elseif ($order->pay_type == 3){
            $result = false;
            $msg = "";
            Db::startTrans();
            try {
                $buyNumber = \app\common\func\Order::getBuyNumber($order->user_id);

                $buyNumber->nums += $order->total_num;
                $buyNumber->save();

                $order->pay_state = 4;
                $order->save();

                $result = true;

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $msg = $e->getMessage();
            }

            if ($result) {
                $this->success("取消成功！");
            } else {
                $this->error("取消失败:" . $msg);
            }
        }else{
            $this->error("支付类型错误，请联系管理员");
        }
    }

    // 修改订单收货地址
    public function editOrderAddress() {
        $orderId = $this->request->post("order_id");
        $addressId = $this->request->post("address_id");
        if ($orderId > 0 && $addressId > 0) {
            $address = UserAddress::where(["id" => $addressId])->find();
            $orderAddressData = OrderAddress::where(["user_id" => $this->auth->id, "order_id" => $orderId])->find();
            if (!empty($orderAddressData)) {
                $orderAddressData->name = $address->name;
                $orderAddressData->mobile = $address->mobile;
                $orderAddressData->address = $address->province . $address->city . $address->district . $address->address;
                $orderAddressData->save();
            } else {
                $orderAddressDatas = new OrderAddress();
                $orderAddressDatas->user_id = $this->auth->id;
                $orderAddressDatas->order_id = $orderId;
                $orderAddressDatas->name = $address->name;
                $orderAddressDatas->mobile = $address->mobile;
                $orderAddressDatas->address = $address->province . $address->city . $address->district . $address->address;
                $orderAddressDatas->save();
            }
            $this->success("修改成功");
        } else {
            $this->error("参数错误");
        }
    }
}
